<?php
class AttachmentController extends Controller
{
	public function actionDownload()
	{
		$id = $this->getParam ( 'id' );
		$key = $this->getParam ( 'key' );
		
		if ($key != md5 ( Yii::app ()->user->secretKey . $id ))
		{
			throw new CHttpException ( 404, "下载文件操作错误!" );
		}
		$model = new Attachment ();
		$data = $model->findByPk ( $id );
		if (! $data)
			return false;
			
			// $filename = Yii::app ()->params ['uploadPath'] . $data->path;
		$filename = $this->getConfig ( 'uploadPath' ) . $data->path;
		
		// 检查文件是否存在
		if (! file_exists ( $filename ))
		{
			
			Yii::log ( '找不到文件:' . $filename, CLogger::LEVEL_ERROR, 'application.controllers.Attachment.download' );
			throw new CHttpException ( 404, "文件找不到" );
		} else
		{
			header ( 'Content-Description: File Transfer' );
			header ( 'Content-Type: application/octet-stream' );
			header ( 'Content-Disposition: attachment; filename=' . urlencode ( $data->filename ) );
			header ( 'Content-Transfer-Encoding: binary' );
			header ( 'Expires: 0' );
			header ( 'Cache-Control: must-revalidate' );
			header ( 'Pragma: public' );
			header ( 'Content-Length: ' . filesize ( $filename ) );
			ob_clean ();
			flush ();
			readfile ( $filename );
			/*
			 * // $file = fopen ( $filename, "r" ); // 打开文件 header (
			 * 'Content-Type: application/force-download' ); header (
			 * 'Content-Type: application/octet-stream' ); header (
			 * 'Content-Type: application/download' ); header (
			 * 'Content-Description: File Transfer' ); // header (
			 * "Accept-Ranges: bytes" ); header ( "Accept-Length: " . filesize (
			 * $filename ) ); // Header ( "Content-Disposition: attachment;
			 * filename=" . iconv ( // 'utf-8', 'gb2312', $data->filename ) );
			 * header ( "Content-Disposition: attachment; filename=" . urlencode
			 * ( $data->filename ) ); //echo file_get_contents ( $filename );
			 * readfile($filename);
			 */
			// echo fread ( $file, filesize ( $filename ) );
			// fclose ( $file );
			// exit ();
			Yii::app ()->end ();
		}
	}
}
?>